package cn.fl.customer.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstMidManInfoService;
import cn.fl.customer.vo.CstMidManInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.constant.SysLogConstant;
import fl.customer.facade.customer.condition.CstMidManInfoQueryCondition;

/**
 * @Description: 客户中间人信息表 控制层
 */
@Controller
@RequestMapping("/customer/cstmidmaninfo")
public class CstMidManInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CstMidManInfoController.class);

	/**
	 * CstMidManInfo 服务层BEAN
	 */
	@Autowired
	private ICstMidManInfoService cstMidManInfoService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		ModelAndView view = new ModelAndView("customer/cstmidmaninfo/cstMidManInfoList");
		view.addObject("cstId", cstId);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到查看列表页面
	 */
	@RequestMapping(value = "/toDetailListPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailListPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		ModelAndView view = new ModelAndView("customer/cstmidmaninfo/cstMidManInfoDetailList");
		view.addObject("cstId", cstId);
		BaseLogUtils.info(logger, "toDetailListPage", "跳转到查看列表页面. cstId" + cstId, CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到新增/修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET})
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String cstId = request.getParameter("cstId");
		ModelAndView view = new ModelAndView("customer/cstmidmaninfo/cstMidManInfoAdd");
		view.addObject("mId", id);
		view.addObject("cstId", cstId);
		BaseLogUtils.info(logger, "toAddPage", "跳转到新增/修改页面.[id="+id+", cstId="+cstId+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("customer/cstmidmaninfo/cstMidManInfoDetail");
		view.addObject("mId", id);
		BaseLogUtils.info(logger, "toDetailPage", "跳转到详情页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstId = request.getParameter("cstId");
		
		//如果客户ID有问题则直接返回空集合
		if(StringUtils.isBlank(cstId) || !StringUtils.isNumeric(cstId)){
			BaseLogUtils.info(logger, "initList", "客户主键参数不存在,直接返回空集合.", CurrentThreadContext.getCurrentUserName());
			return new ListPageVO<CstMidManInfoVO>();
		}
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CstMidManInfoQueryCondition qc = new CstMidManInfoQueryCondition();
		qc.setCstId(Long.valueOf(cstId));//客户ID必须要传,如果不符合条件则不能进行查询
		//List<String> orgCdList = new ArrayList<>();
		//orgCdList.add(CurrentThreadContext.getCurrentOrgCd());
		//qc.setOrgCdList(orgCdList);
		qc.setCurrUsrId(CurrentThreadContext.getCurrentUserId());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		page.setCondition(qc);
		Pager pager = this.cstMidManInfoService.searchListPage(page);
		List<CstMidManInfoVO> list = (List<CstMidManInfoVO>) pager.getResultList();
		ListPageVO<CstMidManInfoVO> listPage = new ListPageVO<CstMidManInfoVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "初始化列表数据.", CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeById", "删除主键参数不存在.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			this.cstMidManInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage() + ", ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CstMidManInfoVO vo = this.cstMidManInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage()+ ", ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			CstMidManInfoVO entity = this.getRequestParms(request);
			entity.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			entity.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			Long id = this.cstMidManInfoService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败."+ex.getMessage()+ ", ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			CstMidManInfoVO entity = this.getRequestParms(request);
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			boolean success = this.cstMidManInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"]"+ex.getMessage()+ ", ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取公共参数
	 */
	private CstMidManInfoVO getRequestParms(HttpServletRequest request){
		String mNm = request.getParameter("mNm");
		String mMp = request.getParameter("mMp");
		String mIdNo = request.getParameter("mIdNo");
		String mRem = request.getParameter("mRem");
		String cstId = request.getParameter("cstId");
		
		if (StringUtils.isBlank(cstId)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "客户ID不能为空!");
		}
		
		if (StringUtils.isBlank(mNm) || mNm.length() > 20 || !StringUtils.isCustomerName(mNm)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604,
							"姓名不能为空,支持格式[艾合买提•倪格提],并且长度不能大于20个字符。");
		}
		
		if (StringUtils.isBlank(mMp) || !StringUtils.checkMobileNumber(mMp)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请输入正确的手机号码1!");
		}
		
		String certTypCd = DictionaryConstant.CODE_CERT_TYP_CD_0;//默认自然人证件类型为身份证 request.getParameter("certTypCd");// 证件类型
		
		if (StringUtils.isBlank(mIdNo)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "证件号码不能为空!");
		}

		if (certTypCd.equals(DictionaryConstant.CODE_CERT_TYP_CD_0) && !StringUtils.isIdCardNumber(mIdNo)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请输入正确的身份证号码!");
		}
		
		if(StringUtils.isNotBlank(mRem) && mRem.length() > 100){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "备注长度不能大于100个字符!");
		}
		
		CstMidManInfoVO cstMidManInfoVO = new CstMidManInfoVO();
		cstMidManInfoVO.setMNm(mNm);
		cstMidManInfoVO.setMMp(mMp);
		cstMidManInfoVO.setMIdNo(mIdNo);
		cstMidManInfoVO.setMRem(mRem);
		cstMidManInfoVO.setCstId(Long.valueOf(cstId));
		return cstMidManInfoVO;
	}
}

